package cn.tude._05mvcboot04.controller;


import cn.tude._05mvcboot04.base.response.JsonResult;
import cn.tude._05mvcboot04.base.response.StatusCode;
import cn.tude._05mvcboot04.mapper.UserMapper;
import cn.tude._05mvcboot04.pojo.dto.UserLoginDTO;
import cn.tude._05mvcboot04.pojo.dto.UserRegDTO;
import cn.tude._05mvcboot04.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("v1/users/login")
@Api(tags = "01.用户模块")

public class UserController {
    @Autowired(required = false)
    private UserMapper userMapper;


    @PostMapping("login")
    @ApiOperation("1.登录")
    public JsonResult login(@RequestBody @Validated UserLoginDTO loginDTO, @ApiIgnore HttpSession session){
        UserVO userVO=userMapper.selectByUsername(loginDTO.getUsername());
        if (userVO==null){
            return new JsonResult(StatusCode.USERNAME_ERROR);
        }
        if (loginDTO.getPassword().equals(userVO.getPassword())){
            session.setAttribute("user",userVO);
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
    }


    @PostMapping("reg")
    @ApiOperation("2.注册")
    public JsonResult reg(@Validated @RequestBody UserRegDTO userRegDTO){
        UserVO  userVO=userMapper.selectByUsername(userRegDTO.getUsername());
        if (userVO==null){
            int i = userMapper.insertUser(userRegDTO);
            if (i==1)
                return JsonResult.ok();
            return JsonResult.notok();
        }
        return new JsonResult(StatusCode.USERNAME_EXIT);
    }


    @GetMapping("currentUser")
    @ApiOperation(value="3.当前登录用户")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        return JsonResult.ok(session.getAttribute("user"));
    }



}
